package com.beta.auth.config;

import com.beta.auth.constants.AuthChannel;
import com.beta.auth.utils.JwtUtil;
import com.beta.mq.redis.user.CurrentUserInvoker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author gwqin
 * @description 用户解析，获取当前授权的用户ID
 * @date 2023-11-09 14:26
 */
@Component
public class AuthUserInvoker implements CurrentUserInvoker {

    @Autowired
    private UserAuthCfgBean userAuthCfgBean;

    @Override
    public String getCurrentUserId(HttpServletRequest request, HttpServletResponse response) {
        String location = response.getHeader("Location");
        if (StringUtils.isEmpty(location)) {
            return StringUtils.EMPTY;
        }

        String secret = null;
        String state = request.getParameter("state");
        if (StringUtils.isEmpty(state)) {
            return StringUtils.EMPTY;
        }

        String[] splits = state.split("_");
        String authChannel = splits[0];
        if (StringUtils.equals(authChannel, AuthChannel.MP.getChannel())) {
            secret = userAuthCfgBean.getMpJwtSecret();
        } else if (StringUtils.equals(authChannel, AuthChannel.SELF_APP.getChannel())) {
            secret = userAuthCfgBean.getJwtSecret();
        } else {
            return StringUtils.EMPTY;
        }

        String[] params = location.split("&", -1);
        for (String param : params) {
            if (param.startsWith("bjwt=")) {
                String bjwt = param.substring(5);
                Map<String, String> decrypted = JwtUtil.decrypt(secret, bjwt);
                return decrypted.get("userId");
            }
        }

        return StringUtils.EMPTY;
    }

}
